package org.jiuling.validation;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.jiuling.basics.validation.ArrayVerify;
import org.jiuling.basics.validation.ListVerify;
import org.jiuling.basics.validation.SetVerify;
import org.jiuling.basics.validation.StringVerify;
import org.jiuling.validation.exception.ValidationException;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 校验
 * @author 紫灵
 * @date 2024年12月26日 10时50分07秒
 */
public class Validation {

    /**
     * 直接校验
     * @param t 泛型对象
     * @param groups 校验组
     * @param <T> 泛型对象类型
     * @throws ValidationException 校验异常
     */
    public static <T> void directVerification(T t,Class<?>... groups) throws ValidationException {
        ValidatorFactory factory = jakarta.validation.Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        // 判断校验组是否为空，如果为空则不指定校验组
        Set<ConstraintViolation<T>> violations = ArrayVerify.isEmpty(groups) ? validator.validate(t) : validator.validate(t,groups);
        if (!SetVerify.isEmpty(violations)) {
            String collect = violations.stream().map(
                    violation -> violation
                            .getMessage()
                            .replace("!", "")
                            .replace("！", "")
            ).collect(Collectors.joining("、")).concat("！");
            if (!StringVerify.isBlank(collect)){
                throw new ValidationException(collect);
            }
        }
    }

    /**
     * 直接校验
     * @param t 泛型对象
     * @param <T> 泛型对象类型
     * @throws ValidationException 校验异常
     */
    public static <T> void directVerification(T t) throws ValidationException {
        ValidatorFactory factory = jakarta.validation.Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        // 判断校验组是否为空，如果为空则不指定校验组
        Set<ConstraintViolation<T>> violations = validator.validate(t);
        if (!SetVerify.isEmpty(violations)) {
            String collect = violations.stream().map(
                    violation -> violation
                            .getMessage()
                            .replace("!", "")
                            .replace("！", "")
            ).collect(Collectors.joining("、")).concat("！");
            if (!StringVerify.isBlank(collect)){
                throw new ValidationException(collect);
            }
        }
    }


}
